package de.fhk.fst.dvr.user

import de.fhk.fst.dvr.association.UserGroupAssociation

class User {

  String username;
  String firstname;
  String lastname;
  String email;
  String password;
  Date dateOfBirth;

  static hasMany = [groups: UserGroupAssociation]

  static transients = ["admin"]

  static constraints = {
    username(nullable: false, blank: false, maxLength: 20, unique: true)
    firstname(nullable: false, blank: false, maxLength: 32)
    lastname(nullable: true, blank: true, maxLength: 32)
    email(email: true, nullable: false, blank: false, maxLength: 64, unique: true)
    password(nullable: false, blank: false, minLength: 6)
  }

  def beforeInsert() {
    password = password.encodeAsSHA()
    if(groups == null) {
      groups = new HashSet<UserGroupAssociation>()
    }
    groups.add(new UserGroupAssociation(user: this, group: UserGroup.findById(2)))
  }

  def beforeUpdate() {
    password = password.encodeAsSHA()
  }

  public boolean isAdmin() {
    for (UserGroupAssociation group : groups) {
      return group.isAdminGroup();
    }
    return false;
  }

  public String toString() {
    return username;
  }
}
